/*
 * @(#) NewsDaoImpl.java 1.0  2011-8-17 
 *
 * (c) Copyright 2011 smshen S3H3L3
 *
 * FILENAME    : NewsDaoImpl.java
 * PACKAGE     : com.sm.dao.impl
 * CREATE DATE : 2011-8-17
 * AUTHOR      : smshen
 */

package com.sm.dao.impl;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.sm.dao.NewsDao;
import com.sm.model.News;
import com.sm.util.DataGrid;
import com.sm.util.JsonUtil;

/*******************************************************************************
 *  #(c) smshen S3H3L3 
 *
 *  功能说明: 
  
 *  2011-8-17 下午5:16:04 smshen 创建文件
 * 
 *  修改说明: 创建文件

 *  2011-8-17 下午5:16:04 smshen 修改文件
 * 
 ******************************************************************************/

public class NewsDaoImpl extends HibernateDaoSupport implements NewsDao {

	@Override
	public void addNews(News news) {
		getHibernateTemplate().save(news);

	}

	@Override
	public void delNews(int id) {
		getHibernateTemplate().delete(getNews(id));

	}

	@Override
	public News getNews(int id) {
		return getHibernateTemplate().get(News.class, id);
	}

	@Override
	public String getAllNews(HttpServletRequest request) {
		DataGrid dataGrid = new DataGrid();
		String page = request.getParameter("page");
		String rows = request.getParameter("rows");
		int indexStart = (Integer.valueOf(page) - 1) * Integer.valueOf(rows);
		String hql = "FROM News";
		Query query = getSession().createQuery(hql);
		dataGrid.setTotal(query.list().size());
		
		query.setFirstResult(indexStart);
		query.setMaxResults(Integer.valueOf(rows));
		dataGrid.setRows(query.list());
		return JsonUtil.object2Json(dataGrid);
	}

	@Override
	public void updateAndSaveNews(News news) {
		getHibernateTemplate().saveOrUpdate(news);

	}

	@SuppressWarnings("unchecked")
	@Override
	public List<News> getAllNews() {
		String hql = "FROM News";
		Query query = getSession().createQuery(hql);
		return query.list();
	}

}


